<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="分配角色权限"
    :close-func="closeFunc"
    destroyOnClose
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #deptIds="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :fieldNames="{ title: 'title', key: 'id' }"
          :checkable="model.roleKey !== SUPER_ADMIN_KEY"
          toolbar
          title="菜单权限"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { menuSchema } from './data';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { authRoleApi, getRoleAuthApi } from '@/api/system/role';
  import { listPortionMenuApi } from '@/api/system/menu';
  import { SUPER_ADMIN_KEY, type SystemRoleItem } from '@/api/system/model/roleModel';
  import {
    findCompletelySelectedOrChildlessIds,
    getParentsOfChosenNodes,
  } from '@/hooks/component/useTree';

  const isUpdate = ref(true);
  const rowId = ref('');
  const treeData = ref<TreeItem[]>([]);
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate, setProps }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: menuSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    function disabled(arr: any) {
      arr.forEach((item) => {
        item.disabled = item.resStatus == 1;
        if (item.children) {
          disabled(item.children);
        }
      });
    }
    resetFields();
    const isAdmin = data.roleKey === SUPER_ADMIN_KEY;
    setModalProps({ confirmLoading: false });
    setModalProps({ okButtonProps: { disabled: isAdmin } });
    setProps({ disabled: isAdmin });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await listPortionMenuApi()) as any as TreeItem[];
      disabled(treeData.value);
    }
    const { id } = data;
    rowId.value = id;
    if (id) {
      const deptData = (await getRoleAuthApi(id)) as any as string[];
      const completelySelectedOrChildlessIds = findCompletelySelectedOrChildlessIds<TreeItem>(
        treeData.value,
        deptData,
      );
      setFieldsValue({ ...data, deptIds: completelySelectedOrChildlessIds });
    }
  });

  const closeFunc = async () => {
    await resetFields();
    return true;
  };

  async function handleSubmit() {
    try {
      const values: SystemRoleItem = await validate();
      setModalProps({ confirmLoading: true });
      const resIds = values.deptIds || [];
      const halfCheckedKeys = getParentsOfChosenNodes(values.deptIds || [], treeData.value);

      // TODO custom api
      await authRoleApi({
        resIds: Array.from(new Set([...resIds, ...halfCheckedKeys])),
        roleId: rowId.value,
      });

      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
